package TcpDemon02;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClientDemon02 {
    public static void main(String[] args) {
        try(
                // 1. create Socket connection
                Socket socket=new Socket(InetAddress.getByName("127.0.0.1"),9000);
                // 2. create OutputStream
                OutputStream os=socket.getOutputStream();
                // 3. read certain file
                FileInputStream fis=new FileInputStream(new File("0713.jpg"));
                // 6. make sure
                InputStream is=socket.getInputStream();
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                ){
            // 4. write file
            byte[] buffer=new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1){
                os.write(buffer,0,len);
            }
            // 5. notice have done
            socket.shutdownOutput();
            // 6. make sure serverSocket accept all,then break connection
            byte[] buffer2=new byte[1024];
            int len2;
            while((len2=is.read(buffer2))!=-1){
                baos.write(buffer2,0,len2);
            }
            System.out.println(baos.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
